package com.usaas.search.component;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.usaas.common.core.redis.RedisCache;
import com.usaas.search.dto.PlatUserDto;
import com.usaas.search.pojo.PlatUserPojo;
import com.usaas.search.service.IPlatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Component
public class AppTokenComponent {
    static final String SEARCH_APP_TOKEN = "search-app-token";


    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPlatUserService platUserService;

    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(SEARCH_APP_TOKEN);
        return token;
    }

    public String getToken() {
        return UserContextHolder.getToken();
    }

    public PlatUserDto getUserInfo(HttpServletRequest request) {
        String token = getToken(request);
        if (StrUtil.isNotBlank(token)) {
            String userInfoJson = redisCache.getCacheObject(token);
            if (StrUtil.isNotBlank(userInfoJson)) {
                return JSON.parseObject(userInfoJson, PlatUserDto.class);
            }
        }
        return null;
    }

    public void updateUserInfo(HttpServletRequest request, PlatUserDto userDto) {
        String token = getToken(request);
        this.refreshUserInfo(token, userDto);
    }

    public PlatUserDto getUserInfo() {
        return UserContextHolder.get();
    }

    public Long getUserId() {
        return getUserInfo().getId();
    }

    public PlatUserDto getUserInfoWithError() {
        PlatUserDto platUserDto = UserContextHolder.get();
        Assert.notNull(platUserDto, "请重新登录");
        return platUserDto;
    }


    public void forceRefreshCurrentUserInfo() {
        Long userId = getUserId();
        String token = getToken();
        PlatUserPojo platUser = platUserService.getById(userId);
        PlatUserDto userInfo = BeanUtil.copyProperties(platUser, PlatUserDto.class);
        refreshUserInfo(token, userInfo);
    }

    public void refreshUserInfo(String token, PlatUserDto userInfo) {
        redisCache.setCacheObject(token, JSON.toJSONString(userInfo), 7, TimeUnit.DAYS);
    }

    public void removeToken(HttpServletRequest request) {
        String token = getToken(request);
        redisCache.deleteObject(token);
    }
}
